package com.ruoyi.web.controller.system;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.ClientInfoStatus;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.publish.domain.IdAcceptRegister;
import com.ruoyi.publish.service.IIdAcceptRegisterService;
import com.ruoyi.web.controller.tool.HttpRequestUtil;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.hibernate.validator.internal.util.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JsonParseException;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysRole;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Controller
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Value("${ruoyi.tokenPath}")
    private String tokenUrl;

    private String prefix = "system/user";

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IIdAcceptRegisterService idAcceptRegisterService;

    @RequiresPermissions("system:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    //    @RequiresPermissions("system:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 根据角色ID查询用户
     */
//    @RequiresPermissions("system:user:headmanList")
    @GetMapping("/headmanList/{roleId}")
    @ResponseBody
    public TableDataInfo headmanList(@PathVariable("roleId") Long roleId, ModelMap modelMap) {
        return getDataTable(userService.selectUserByRoleID(roleId));
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(SysUser user) {
        List<SysUser> list = null;
        if (StringUtils.isNotEmpty(user.getExportIds())) {
            list = userService.selectRecordByIds(user.getExportIds().split(","));
        } else {
            list = userService.selectUserList(user);
        }

        list.forEach(item -> {
            item.setExportRoles(item.getExportRoles());
        });

        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);

        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> list = new ArrayList<>();
        SysUser sysUser = new SysUser();
        //用户序号
        sysUser.setUserId(Long.valueOf("1"));
        //部门编号
        sysUser.setDeptId(Long.valueOf("103"));
        //登录名称
        sysUser.setLoginName("ry(示范)");
        //用户名称
        sysUser.setUserName("若依(示范)");
        //用户邮箱
        sysUser.setEmail("ry@163.com(示范)");
        //手机号码
        sysUser.setPhonenumber("15888888888(示范)");
        //用户性别
        sysUser.setSex("1");
        //帐号状态
        sysUser.setStatus("0");
        //角色ID
        sysUser.setStrRoles("2(示范)");
        list.add(sysUser);
        return util.importDataTemplateExcel(list, "用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated SysUser user) {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
//        else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
//        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
//        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{userId}")
    public String edit(@PathVariable("userId") Long userId, ModelMap mmap) {
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", userService.selectUserById(userId));
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(userId));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated SysUser user) {
        userService.checkUserAllowed(user);
//        if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
//            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
//        } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
//            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
//        }
        user.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(userService.updateUser(user));
    }

    @RequiresPermissions("system:user:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap) {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(SysUser user) {
        userService.checkUserAllowed(user);
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0) {
            if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue()) {
                ShiroUtils.setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") Long userId, ModelMap mmap) {
        SysUser user = userService.selectUserById(userId);
        // 获取用户所属的角色列表
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", user);
        mmap.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @RequiresPermissions("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(userService.deleteUserByIds(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(SysUser user) {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(SysUser user) {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(SysUser user) {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(SysUser user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.changeStatus(user));
    }

    /**
     *鉴定组长 查询
     */


    /**
     * 新增保存用户
     */

    @Log(title = "外网添加管理员", businessType = BusinessType.INSERT)
    @PostMapping("/addAdmin")
    @ResponseBody
    public AjaxResult addAdmin(HttpServletRequest request) {


        String token = request.getParameter("token");
        String userName = request.getParameter("userName");
        String loginName = request.getParameter("loginName");
        String password = request.getParameter("password");

        if (StringUtils.isEmpty(token)) {
            return error("token 不能为空");

        }
        if (StringUtils.isEmpty(loginName)) {
            return error("登陆账号不能为空");

        }

        password = loginName + "@cb";
        Long[] role = {2L};
        SysUser user = new SysUser();
        user.setUserName(userName);
        user.setLoginName(loginName);
        user.setRoleIds(role);
        user.setPassword(password);


        String json;
//        String username = null;
        try {
            json = HttpRequestUtil.sendGet(tokenUrl, token);
            System.out.println(json);

            ObjectMapper mapper = new ObjectMapper();
            try {
//				s productMap = mapper.readValue(json,s.class);
                Map<String, Object> m = mapper.readValue(json, Map.class);
                System.out.println(m);
                if (m.get("username") != null) {
                    String outName = m.get("username").toString();

                    if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName()))) {
                        return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
                    } else if (UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
                        return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
                    } else if (UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
                        return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
                    }
                    user.setSalt(ShiroUtils.randomSalt());
                    user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
                    user.setCreateBy("外网创建" + outName);
                    return toAjax(userService.insertUser(user));

                } else {
                    System.out.println("未获得数据");

                }
                if (m.get("errcode") != null) {
                    System.out.println("返回错误");
                    System.out.println(m.get("errmsg"));
                }
            } catch (JsonParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//转成map
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        return error("新增用户失败");

    }

    /**
     * 审核记录 关联按键选择 单选
     */
    @GetMapping("/userSelect")
    public String checkRadio() {
        return prefix + "/userSelect";
    }

    /**
     * 审核记录 关联按键选择 单选
     */
    @GetMapping("/userSelectPage/{userId}")
    public String userSelectPage(@PathVariable("userId") Long userId, ModelMap mmap) {

        mmap.addAttribute("userId", userId);
        return prefix + "/userSelectPage";
    }


    /**
     * 选择鉴定组长
     */
    @GetMapping("/userGroupSelect/{groupId}")
    public String userGroupSelect(@PathVariable("groupId") String groupId, ModelMap mmap) {
        // 鉴定组长

        // 获取最新的鉴定组长
        if ("0".equals(groupId)) {
            String groupIdNews = idAcceptRegisterService.selectTopNewGroupId();
            if (StringUtils.isNotEmpty(groupIdNews)) {
                groupId = groupIdNews;
            }
        }
        mmap.addAttribute("selectGroupId", groupId);
        return prefix + "/userGroupSelect";
    }


    @PostMapping("/getGroupList/{groupId}")
    @ResponseBody
    public TableDataInfo getGroupList(@PathVariable("groupId") Long groupId, SysUser user) {
        startPage();
        List<SysUser> list = userService.selectGroupUser(groupId,user);
        return getDataTable(list);
    }

    @PostMapping("/getApprovalUserList/{userId}")
    @ResponseBody
    public TableDataInfo getApprovalUserList(@PathVariable("userId") Long userId, SysUser user) {
        startPage();
        List<SysUser> list = userService.getApprovalUserList(userId,user);
        return getDataTable(list);
    }

    @GetMapping("/getAvatar/{userId}")
    public void getAvatar(@PathVariable("userId") Long userId, HttpServletRequest request, HttpServletResponse response) throws IOException {

        if (userId==null){
            return ;
        }
        SysUser  user=userService.selectUserById(userId);
        if (user==null){
            return ;

        }
        String fileName="";
        String imgFile="";
        if (StringUtil.isNotEmpty(user.getAvatar())){
            fileName=user.getAvatar();
             imgFile = Global.getProfile() + "/" +  fileName.substring(9);
            System.out.println(imgFile);
        }
        

//        String imgType = fileName.substring(fileName.indexOf('.') + 1 , fileName.length());
        String imgType ="png";
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");

        response.setContentType("image/"+imgType);

        BufferedImage bi = null;;
        ServletOutputStream out = response.getOutputStream();

        try {
            if (StringUtil.isNotEmpty(user.getAvatar())){
                bi = ImageIO.read(new File(imgFile));

            }else{
                bi = getCrystalImage(1, 1);   //如果没有该文件，则显示默认的透明图片

            }
            //把读过的来的图片画到设定好的新图片上
            ImageIO.write(bi, imgType, out);
        } catch (IIOException e) {
            logger.info("读取不出图片:"+imgFile, e);
            bi = getCrystalImage(1, 1);   //如果没有该文件，则显示默认的透明图片
            ImageIO.write(bi, "png", out);
//            throw new ServiceException("读取不出图片");   //ServiceException是自己定义的异常，可忽略。
        } finally {
            try {
                out.flush();
            } finally {
                out.close();
            }
        }
    }


    public static BufferedImage getCrystalImage(Integer width, Integer height){
        width = width==null?710 : width;
        height = height == null ? 285: height;

        // 创建BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取Graphics2D
        Graphics2D g2d = image.createGraphics();
        // ---------- 增加下面的代码使得背景透明 -----------------
        image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g2d.dispose();
        g2d = image.createGraphics();
        // ---------- 背景透明代码结束 -----------------
        // 画图
        g2d.setColor(Color.WHITE);
        g2d.setStroke(new BasicStroke(1));
        //释放对象
        g2d.dispose();

        return image;
    }
}